package com.nbsaas.boot.order.rest.resource;

import com.nbsaas.boot.order.api.apis.OrderQueryApi;
import com.nbsaas.boot.order.api.domain.response.OrderResponse;
import com.nbsaas.boot.order.data.entity.Order;
import com.nbsaas.boot.order.rest.convert.OrderResponseConvert;
import com.nbsaas.boot.order.service.OrderQueryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 订单查询资源类
 * 使用Freemarker动态生成
 */
@Transactional
@Service
public class OrderQueryResource implements OrderQueryApi {

    @Resource
    private OrderQueryService orderQueryService;

    @Resource
    private OrderResponseConvert orderResponseConvert;

    @Override
    public List<OrderResponse> findOrdersByShopAndState(Long shopId, Integer orderState) {
        List<Order> orders = orderQueryService.findOrdersByShopAndState(shopId, orderState);
        return orders.stream()
                .map(orderResponseConvert)
                .collect(Collectors.toList());
    }

    @Override
    public Map<String, Object> getOrderStatistics(Long shopId, String startDate, String endDate) {
        LocalDateTime start = parseDateTime(startDate);
        LocalDateTime end = parseDateTime(endDate);
        return orderQueryService.getOrderStatistics(shopId, start, end);
    }

    @Override
    public List<OrderResponse> findOrdersByCustomer(Long customerId, Long shopId) {
        List<Order> orders = orderQueryService.findOrdersByCustomer(customerId, shopId);
        return orders.stream()
                .map(orderResponseConvert)
                .collect(Collectors.toList());
    }

    @Override
    public List<Map<String, Object>> findOrdersByPayState(Integer payState, Long shopId, String startDate) {
        LocalDateTime start = parseDateTime(startDate);
        return orderQueryService.findOrdersByPayState(payState, shopId, start);
    }

    @Override
    public List<Map<String, Object>> getOrderStatisticsByDate(Long shopId, String startDate, String endDate) {
        LocalDateTime start = parseDateTime(startDate);
        LocalDateTime end = parseDateTime(endDate);
        return orderQueryService.getOrderStatisticsByDate(shopId, start, end);
    }

    @Override
    public List<Map<String, Object>> findOrdersWithCoupon(Long shopId, String startDate) {
        LocalDateTime start = parseDateTime(startDate);
        return orderQueryService.findOrdersWithCoupon(shopId, start);
    }

    @Override
    public List<Map<String, Object>> findOrdersWithVipCard(Long shopId) {
        return orderQueryService.findOrdersWithVipCard(shopId);
    }

    @Override
    public List<Map<String, Object>> getOrderStatisticsBySource(Long shopId, String startDate, String endDate) {
        LocalDateTime start = parseDateTime(startDate);
        LocalDateTime end = parseDateTime(endDate);
        return orderQueryService.getOrderStatisticsBySource(shopId, start, end);
    }

    @Override
    public List<Map<String, Object>> findRefundOrders(Long shopId) {
        return orderQueryService.findRefundOrders(shopId);
    }

    @Override
    public List<Map<String, Object>> findOrdersWithIntegral(Long shopId, String startDate) {
        LocalDateTime start = parseDateTime(startDate);
        return orderQueryService.findOrdersWithIntegral(shopId, start);
    }

    @Override
    public List<Map<String, Object>> findOrdersWithRedPacket(Long shopId) {
        return orderQueryService.findOrdersWithRedPacket(shopId);
    }

    @Override
    public List<Map<String, Object>> getOrderStatisticsByHour(Long shopId, String startDate, String endDate) {
        LocalDateTime start = parseDateTime(startDate);
        LocalDateTime end = parseDateTime(endDate);
        return orderQueryService.getOrderStatisticsByHour(shopId, start, end);
    }

    @Override
    public List<Map<String, Object>> getOrderStatisticsByState(Long shopId, String startDate, String endDate) {
        LocalDateTime start = parseDateTime(startDate);
        LocalDateTime end = parseDateTime(endDate);
        return orderQueryService.getOrderStatisticsByState(shopId, start, end);
    }

    @Override
    public List<Map<String, Object>> getOrderStatisticsByPayMethod(Long shopId, String startDate, String endDate) {
        LocalDateTime start = parseDateTime(startDate);
        LocalDateTime end = parseDateTime(endDate);
        return orderQueryService.getOrderStatisticsByPayMethod(shopId, start, end);
    }

    @Override
    public List<Map<String, Object>> getOrderCompleteTimeStatistics(Long shopId, String startDate) {
        LocalDateTime start = parseDateTime(startDate);
        return orderQueryService.getOrderCompleteTimeStatistics(shopId, start);
    }

    @Override
    public List<OrderResponse> findOrdersByConditions(Map<String, Object> conditions) {
        List<Order> orders = orderQueryService.findOrdersByConditions(conditions);
        return orders.stream()
                .map(orderResponseConvert)
                .collect(Collectors.toList());
    }

    @Override
    public Long getOrderCountByShop(Long shopId) {
        return orderQueryService.getOrderCountByShop(shopId);
    }

    @Override
    public BigDecimal getOrderTotalAmount(Long shopId, String startDate, String endDate) {
        LocalDateTime start = parseDateTime(startDate);
        LocalDateTime end = parseDateTime(endDate);
        return orderQueryService.getOrderTotalAmount(shopId, start, end);
    }

    @Override
    public BigDecimal getOrderPayAmount(Long shopId, String startDate, String endDate) {
        LocalDateTime start = parseDateTime(startDate);
        LocalDateTime end = parseDateTime(endDate);
        return orderQueryService.getOrderPayAmount(shopId, start, end);
    }

    @Override
    public BigDecimal getOrderAverageAmount(Long shopId, String startDate, String endDate) {
        LocalDateTime start = parseDateTime(startDate);
        LocalDateTime end = parseDateTime(endDate);
        return orderQueryService.getOrderAverageAmount(shopId, start, end);
    }

    @Override
    public Map<String, Object> getComprehensiveOrderStatistics(Long shopId, String startDate, String endDate) {
        LocalDateTime start = parseDateTime(startDate);
        LocalDateTime end = parseDateTime(endDate);
        
        Map<String, Object> comprehensiveStats = new java.util.HashMap<>();
        
        // 基础统计
        Map<String, Object> basicStats = orderQueryService.getOrderStatistics(shopId, start, end);
        comprehensiveStats.putAll(basicStats);
        
        // 按日期统计
        List<Map<String, Object>> dateStats = orderQueryService.getOrderStatisticsByDate(shopId, start, end);
        comprehensiveStats.put("dateStatistics", dateStats);
        
        // 按状态统计
        List<Map<String, Object>> stateStats = orderQueryService.getOrderStatisticsByState(shopId, start, end);
        comprehensiveStats.put("stateStatistics", stateStats);
        
        // 按支付方式统计
        List<Map<String, Object>> payMethodStats = orderQueryService.getOrderStatisticsByPayMethod(shopId, start, end);
        comprehensiveStats.put("payMethodStatistics", payMethodStats);
        
        // 按来源统计
        List<Map<String, Object>> sourceStats = orderQueryService.getOrderStatisticsBySource(shopId, start, end);
        comprehensiveStats.put("sourceStatistics", sourceStats);
        
        // 按小时统计
        List<Map<String, Object>> hourStats = orderQueryService.getOrderStatisticsByHour(shopId, start, end);
        comprehensiveStats.put("hourStatistics", hourStats);
        
        // 优惠券使用统计
        List<Map<String, Object>> couponStats = orderQueryService.findOrdersWithCoupon(shopId, start);
        comprehensiveStats.put("couponStatistics", couponStats);
        
        // 积分使用统计
        List<Map<String, Object>> integralStats = orderQueryService.findOrdersWithIntegral(shopId, start);
        comprehensiveStats.put("integralStatistics", integralStats);
        
        // 会员卡使用统计
        List<Map<String, Object>> vipCardStats = orderQueryService.findOrdersWithVipCard(shopId);
        comprehensiveStats.put("vipCardStatistics", vipCardStats);
        
        // 红包使用统计
        List<Map<String, Object>> redPacketStats = orderQueryService.findOrdersWithRedPacket(shopId);
        comprehensiveStats.put("redPacketStatistics", redPacketStats);
        
        // 退款统计
        List<Map<String, Object>> refundStats = orderQueryService.findRefundOrders(shopId);
        comprehensiveStats.put("refundStatistics", refundStats);
        
        return comprehensiveStats;
    }

    /**
     * 解析日期时间字符串
     * @param dateTimeStr 日期时间字符串
     * @return LocalDateTime对象
     */
    private LocalDateTime parseDateTime(String dateTimeStr) {
        if (dateTimeStr == null || dateTimeStr.trim().isEmpty()) {
            return null;
        }
        
        // 支持多种日期格式
        String[] patterns = {
            "yyyy-MM-dd HH:mm:ss",
            "yyyy-MM-dd'T'HH:mm:ss",
            "yyyy-MM-dd HH:mm",
            "yyyy-MM-dd"
        };
        
        for (String pattern : patterns) {
            try {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
                if (pattern.equals("yyyy-MM-dd")) {
                    return LocalDateTime.parse(dateTimeStr + " 00:00:00", 
                        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                }
                return LocalDateTime.parse(dateTimeStr, formatter);
            } catch (Exception e) {
                // 继续尝试下一个格式
            }
        }
        
        throw new IllegalArgumentException("无法解析日期时间字符串: " + dateTimeStr);
    }

    /**
     * 获取订单响应转换器
     * @return 转换函数
     */
    public Function<Order, OrderResponse> getOrderResponseConvert() {
        return orderResponseConvert;
    }
} 